package com.company.genealogy.web.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.genealogy.web.entity.Statistics;
import com.company.genealogy.web.mapper.StatisticsMapper;
import com.company.genealogy.web.service.MemberService;
import com.company.genealogy.web.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper, Statistics> implements StatisticsService {
    @Autowired
    private MemberService memberService;

    @Override
    public Map<String, Object> getBranchAndGenerationStats(Long clanId) {
        List<Map<String, Object>> branchGenList = memberService.countByBranchAndGeneration(clanId);
        List<Map<String, Object>> branchList = memberService.countByBranch(clanId);
        Map<String, Map<String, Integer>> populationByBranchGeneration = new LinkedHashMap<>();
        for (Map<String, Object> row : branchGenList) {
            String branch = (String) row.get("branchName");
            String gen = String.valueOf(row.get("generation"));
            Integer count = ((Number) row.get("count")).intValue();
            populationByBranchGeneration
                .computeIfAbsent(branch, k -> new LinkedHashMap<>())
                .put(gen, count);
        }
        Map<String, Integer> branchPopulationMap = new LinkedHashMap<>();
        for (Map<String, Object> row : branchList) {
            branchPopulationMap.put((String) row.get("branchName"), ((Number) row.get("count")).intValue());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("populationByBranchGeneration", populationByBranchGeneration);
        result.put("branchPopulationMap", branchPopulationMap);
        return result;
    }
} 